/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mikepenz.iconics.typeface;

import ohos.agp.text.Font;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 根据字体文件创建Font对象工具类
 *
 * @since 2021-05-22
 */
public class FontCreator {
    private static final String TAG = "FontCreator";
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 110, TAG);

    private FontCreator() {
    }

    /**
     * 根据字体文件创建Font对象
     *
     * @param context 上下文
     * @param name 字体文件名
     * @return Font对象
     */
    public static Font createFont(Context context, String name) {
        ResourceManager resManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + name);
        Resource resource;
        try {
            resource = rawFileEntry.openRawFile();
        } catch (IOException e) {
            HiLog.error(LABEL, e.getMessage());
            return null;
        }
        File fontFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), name);
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(fontFile);
            int index;
            final int bufferSize = 1024;
            byte[] bytes = new byte[bufferSize];
            final int endPoint = -1;
            while ((index = resource.read(bytes)) != endPoint) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
        } catch (IOException e) {
            HiLog.error(LABEL, e.getMessage());
            return null;
        } finally {
            try {
                if (resource != null) {
                    resource.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                HiLog.error(LABEL, e.getMessage());
            }
        }
        Font.Builder builder = new Font.Builder(fontFile);
        return builder.build();
    }
}
